// =====================================================================================
//	Copyright (C) 2019 by Jiaxing Shao.All rights reserved.
//	文 件 名:  http_server.cpp
//	作    者:  Jiaxing Shao, 13315567369@163.com
//	版 本 号:  1.0
//	创建时间:  2019年04月01日 23时20分25秒
//	Compiler:  g++
//	描    述:
// =====================================================================================

#include "http_server.h"

#include "http_handle.h"
#include "mongoose.h"

#include <string>

#define GLOG_USE_GLOG_EXPORT
#include <glog/logging.h>

static const char *s_root_dir       = ".";
static const char *s_enable_hexdump = "no";

HttpServer::HttpServer(uint16_t port)
{
    m_address = "http://0.0.0.0:" + std::to_string(port);
    mg_log_set(MG_LL_DEBUG);
    mg_mgr_init(&m_mgr);
}

HttpServer::~HttpServer()
{
    mg_mgr_free(&m_mgr);
}

void HttpServer::callback(mg_connection *c, int ev, void *ev_data, void *fn_data)
{
    HttpServer *pthis = (HttpServer *)fn_data;
    if (ev == MG_EV_HTTP_MSG) {
        struct mg_http_message *hm = (struct mg_http_message *)ev_data;
        if (mg_http_match_uri(hm, "/api/test")) {
            http_handle_test(c, hm);
        } else {
            struct mg_http_serve_opts opts = {0};
            opts.root_dir                  = s_root_dir;
            mg_http_serve_dir(c, hm, &opts);
        }
    }
}

bool HttpServer::start()
{
    struct mg_connection *conn;
    if ((conn = mg_http_listen(&m_mgr, m_address.c_str(), callback, this)) == nullptr) {
        LOG(ERROR) << "Cannot listen on " << m_address << ". Use http://ADDR:PORT or :PORT";
    }
    if (mg_casecmp(s_enable_hexdump, "yes") == 0) {
        conn->is_hexdumping = 1;
    }
    while (true) {
        mg_mgr_poll(&m_mgr, 1000);
    }
    return true;
}
